package com.rongxun.hbwallet.ui.activities;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.rongxun.base.MvpActivity;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.IntentKey;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.hbwallet.mvp.contract.IWalletDetail;
import com.rongxun.hbwallet.mvp.presenter.WalletDetailPresenter;
import com.rongxun.utils.ActivityUtils;
import com.rongxun.utils.EventConf;
import com.rongxun.utils.EventUtil;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.InfoEvent;
import com.rongxun.utils.Md5Utils;
import com.rongxun.utils.PreferenceUtils;
import com.rongxun.utils.StatusBarUtil;
import com.rongxun.utils.ToastUtils;
import com.rongxun.utils.wallet.ETHWallet;
import com.rongxun.view.InputPwdDialog;
import com.rongxun.view.PrivateKeyDerivetDialog;
import com.rongxun.widget.LoadingDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by dwq on 2018/3/26/026.
 * e-mail:lomapa@163.com
 */

public class WalletDetailActivity extends MvpActivity<IWalletDetail.IView, WalletDetailPresenter> implements IWalletDetail.IView {
    @BindView(R.id.toolbar_title)
    TextView       mTitle;
    @BindView(R.id.tv_wallet_address)
    TextView       tvWalletAddress;
    @BindView(R.id.rl_modify_pwd)
    RelativeLayout rlModifyPwd;
    @BindView(R.id.rl_derive_private_key)
    RelativeLayout rlDerivePrivateKey;
    @BindView(R.id.rl_derive_keystore)
    RelativeLayout rlDeriveKeystore;
    @BindView(R.id.btn_delete_wallet)
    RelativeLayout btnDeleteWallet;
    @BindView(R.id.btn_mnemonic_backup)
    RelativeLayout btnMnemonicBackup;
    @BindView(R.id.copy_address)
    Button         mCopyAddress;
    @BindView(R.id.address_qrcode)
    ImageView      mAddressQrcode;
    @BindView(R.id.toolbar)
    Toolbar        mToolbar;
    @BindView(R.id.toolbar_back)
    ImageView      mToolbarBack;
    private long                    walletId;
    private String                  walletPwd;
    private String                  walletAddress;
    private String                  walletName;
    private boolean                 walletIsBackup;
    private InputPwdDialog          inputPwdDialog;
    private String                  walletMnemonic;
    private PrivateKeyDerivetDialog privateKeyDerivetDialog;
    private boolean                 fromList;
    private Dialog                  loadingDialog;
    private ETHWallet               mEthWallet;


    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showLoading(boolean show) {
        if (show)
            loadingDialog.show();
        else
            loadingDialog.cancel();
    }

    @Override
    public void showError(String msg, String errorCode) {

    }

    @Override
    public void checkPermissionsSuccessful(String... permissions) {

    }

    @Override
    public void release() {
        if (loadingDialog != null)
            loadingDialog.cancel();
        if (privateKeyDerivetDialog != null)
            privateKeyDerivetDialog.cancel();
        if (inputPwdDialog != null)
            inputPwdDialog.cancel();
    }

    @NonNull
    @Override
    public WalletDetailPresenter createPresenter() {
        return new WalletDetailPresenter(this);
    }

    @Override
    protected void init() {
        EventUtil.register(this);
        mToolbarBack.setVisibility(View.VISIBLE);
        inputPwdDialog = new InputPwdDialog(this, R.style.inputAlert);
        loadingDialog = LoadingDialog.createLoadingDialog(this, getString(R.string.load), false);
        Intent intent = getIntent();
        mEthWallet = intent.getParcelableExtra(IntentKey.ETH_WALLET);
        walletId = mEthWallet.getId();
        walletPwd = mEthWallet.getPassword();
        walletAddress = mEthWallet.getAddress();
        walletName = mEthWallet.getName();
        walletIsBackup = mEthWallet.getIsBackup();
        walletMnemonic = mEthWallet.getMnemonic();
        fromList = intent.getBooleanExtra(IntentKey.FROM_LIST, false);
        StatusBarUtil.setToolBarPaddingTop(mToolbar, this);
        mTitle.setText(walletName);
        tvWalletAddress.setText(walletAddress);

        getPresenter().createQRCode(walletAddress);

        if (walletIsBackup) {
            btnMnemonicBackup.setVisibility(View.GONE);
        } else {
            btnMnemonicBackup.setVisibility(View.VISIBLE);
        }

        FlyLog.i("wallet pwd:" + walletPwd);
        FlyLog.i("walletAddress:" + walletAddress);
        FlyLog.i("walletMnemonic:" + walletMnemonic);
        FlyLog.i("walletMnemonic:" + mEthWallet.getUserId());
    }

    public void onDestroy() {
        super.onDestroy();
        EventUtil.unregister(this);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_wallet_detail;
    }

    @Override
    public void modifySuccess() {

    }

    @Override
    public void modifyPwdSuccess(ETHWallet wallet) {

    }

    @Override
    public void showDerivePrivateKeyDialog(String privateKey) {
        FlyLog.i("privateKey:" + privateKey);

        ActivityUtils.startActivityWithAnimotion(this,
                new Intent(this, PrivateKeyActivity.class).putExtra(IntentKey.PRIVATEKEY, privateKey));
    }

    @Override
    public void showDeriveKeystore(String keystore) {
        FlyLog.i("keystore" + keystore);

        ActivityUtils.startActivityWithAnimotion(this,
                new Intent(this, DeriveKeystoreActivity.class).putExtra(IntentKey.KEYSTORE, keystore));
    }

    @Override
    public void deleteSuccess(boolean isDelete) {
        // TODO: 2018/8/21 调用删除钱包的接口
        if (isDelete)
            getPresenter().deleteWallet(PreferenceUtils.getString(SPKey.WALLETID_FROM_NETWORK, null));
    }

    @Override
    public void showQRCode(byte[] bytes) {
        Glide.with(WalletDetailActivity.this)
                .load(bytes)
                .into(mAddressQrcode);
    }

    @Override
    public void showDeleteWalletResult() {
        finish();
    }

    @OnClick({R.id.rl_modify_pwd, R.id.btn_mnemonic_backup
            , R.id.btn_delete_wallet, R.id.rl_derive_private_key
            , R.id.rl_derive_keystore
            , R.id.copy_address
            , R.id.toolbar_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_modify_pwd:// 修改密码
                ActivityUtils.startActivityWithAnimotion(this,
                        new Intent(this, ModifyPasswordActivity.class)
                                .putExtra(IntentKey.ETH_WALLET, mEthWallet));
                break;
            case R.id.rl_derive_private_key:// 导出明文私钥
                inputPwdDialog.show();
                inputPwdDialog.setDeleteAlertVisibility(false);
                inputPwdDialog.setOnInputDialogButtonClickListener(new InputPwdDialog.OnInputDialogButtonClickListener() {
                    @Override
                    public void onCancel() {
                        inputPwdDialog.dismiss();
                    }

                    @Override
                    public void onConfirm(String pwd) {
                        if (TextUtils.equals(walletPwd, Md5Utils.md5(pwd))) {
                            getPresenter().deriveWalletPrivateKey(walletId, pwd);
                            inputPwdDialog.dismiss();
                        } else {
                            ToastUtils.showToast(R.string.wallet_detail_wrong_pwd);
                        }
                    }
                });
                break;
            case R.id.rl_derive_keystore:// 导出明文keystore
                inputPwdDialog.show();
                inputPwdDialog.setDeleteAlertVisibility(false);
                inputPwdDialog.setOnInputDialogButtonClickListener(new InputPwdDialog.OnInputDialogButtonClickListener() {
                    @Override
                    public void onCancel() {
                        inputPwdDialog.dismiss();
                    }

                    @Override
                    public void onConfirm(String pwd) {
                        if (TextUtils.equals(walletPwd, Md5Utils.md5(pwd))) {
                            getPresenter().deriveWalletKeystore(walletId, pwd);
                            inputPwdDialog.dismiss();
                        } else {
                            ToastUtils.showToast(R.string.wallet_detail_wrong_pwd);
                        }
                    }
                });
                break;
            case R.id.btn_mnemonic_backup://钱包备份
                inputPwdDialog.show();
                inputPwdDialog.setDeleteAlertVisibility(false);
                inputPwdDialog.setOnInputDialogButtonClickListener(new InputPwdDialog.OnInputDialogButtonClickListener() {
                    @Override
                    public void onCancel() {
                        inputPwdDialog.dismiss();
                    }

                    @Override
                    public void onConfirm(String pwd) {
                        if (TextUtils.equals(walletPwd, Md5Utils.md5(pwd))) {
                            ActivityUtils.startActivityWithAnimotion(WalletDetailActivity.this,
                                    new Intent(WalletDetailActivity.this, MnemonicBackupActivity.class)
                                            .putExtra(IntentKey.ETH_WALLET, mEthWallet));
                            inputPwdDialog.dismiss();
                        } else {
                            ToastUtils.showToast(R.string.wallet_detail_wrong_pwd);
                        }
                    }
                });
                break;

            case R.id.btn_delete_wallet://删除钱包
                inputPwdDialog.show();
                inputPwdDialog.setDeleteAlertVisibility(true);
                inputPwdDialog.setOnInputDialogButtonClickListener(new InputPwdDialog.OnInputDialogButtonClickListener() {
                    @Override
                    public void onCancel() {
                        inputPwdDialog.dismiss();
                    }

                    @Override
                    public void onConfirm(String pwd) {
                        if (TextUtils.equals(walletPwd, Md5Utils.md5(pwd))) {
                            getPresenter().deleteWallet(walletId);
                            inputPwdDialog.dismiss();

                        } else {
                            ToastUtils.showToast(R.string.wallet_detail_wrong_pwd);
                        }
                    }
                });
                break;
            case R.id.copy_address:
                copyAddress();
                break;
            case R.id.toolbar_back:
                onBackPressed();
                break;
        }
    }

    private void copyAddress() {
        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", tvWalletAddress.getText().toString());
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        mCopyAddress.setText(getString(R.string.derive_private_key_already_copy_btn));
        mCopyAddress.setTextColor(Color.WHITE);
        mCopyAddress.setEnabled(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(InfoEvent event) {
        switch (event.id) {
            case EventConf.MODIFY_WALLET_PASSWORD:
                walletPwd = (String) event.obj;
                mEthWallet.setPassword(walletPwd);
                break;
            case EventConf.DELETE_WALLET:
                finish();
                break;
            case EventConf.WALLET_ISBACKUP:
                walletIsBackup = true;
                mEthWallet.setBackup(true);
                btnMnemonicBackup.setVisibility(View.GONE);
                break;
        }
    }

}
